<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div class="top-search">
                <a-form>
                    <a-row>
                        <a-col :span="6">
                            <a-form-item label="优先级" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                <a-select
                                    mode="multiple"
                                    v-model:value="state.filter.priorityList"
                                    :options="[
                                        {
                                            label: 'p0',
                                            value: 'p0'
                                        },
                                        {
                                            label: 'p1',
                                            value: 'p1'
                                        },
                                        {
                                            label: 'p2',
                                            value: 'p2'
                                        }
                                    ]"
                                    allow-clear
                                    placeholder="请选择"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="问题来源" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                <a-select
                                    v-model:value="state.filter.questionSourceList"
                                    mode="multiple"
                                    :options="[
                                        {
                                            label: '400',
                                            value: '400'
                                        },
                                        {
                                            label: '现场反馈',
                                            value: '现场反馈'
                                        },
                                        {
                                            label: '系统自检',
                                            value: '系统自检'
                                        }
                                    ]"
                                    show-search
                                    allow-clear
                                    placeholder="请选择"
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="问题类型" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                <a-select
                                    v-model:value="state.filter.typeList"
                                    mode="multiple"
                                    :max-tag-count="2"
                                    :options="[
                                        {
                                            label: '产品问题',
                                            value: '产品问题'
                                        },
                                        {
                                            label: '数据问题',
                                            value: '数据问题'
                                        },
                                        {
                                            label: '算法问题',
                                            value: '算法问题'
                                        },
                                        {
                                            label: '系统故障',
                                            value: '系统故障'
                                        },
                                        {
                                            label: '产品需求',
                                            value: '产品需求'
                                        },
                                        {
                                            label: '算法需求',
                                            value: '算法需求'
                                        },
                                        {
                                            label: '进度风险',
                                            value: '进度风险'
                                        },
                                        {
                                            label: '质量问题',
                                            value: '质量问题'
                                        }
                                    ]"
                                    show-search
                                    allow-clear
                                    placeholder="请选择"
                                    :field-names="{ label: 'label', value: 'value' }"
                                    :filterOption="
                                        (input, option) => {
                                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="5" offset="1">
                            <a-space>
                                <a-button type="primary" @click="getData">查询</a-button>
                                <a-button type="primary" ghost @click="resetData">重置</a-button>
                                <a-button type="primary" ghost @click="saveAsDefault">存为默认</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <a-modal
                :visible="state.changeDataVisible"
                title="修改备注"
                centered
                @ok="confirmReason"
                @cancel="cancelReason"
            >
                <a-textarea v-model:value="state.changeRemark" :rows="4" />
            </a-modal>
            <div class="body">
                <div class="title">
                    <div class="top-title">水泥配料项目问题&风险</div>
                    <a-space>
                        <div>表头含下划线的字段支持双击表格编辑详细内容</div>
                        <a-button type="primary" @click="handleIssued" :loading="state.downLoading">下发</a-button>
                    </a-space>
                </div>

                <div class="default-table">
                    <a-table
                        :columns="columns"
                        :scroll="{ x: 'max-content', y: 550 }"
                        :data-source="state.tableData"
                        :pagination="false"
                        bordered
                        @resizeColumn="handleResizeColumn"
                    >
                        <template #headerCell="{ column, title }">
                            <template v-if="title == '备注'">
                                <div class="text-line-div">{{ title }}</div>
                            </template>
                        </template>
                        <template #bodyCell="{ record, text, column }">
                            <template v-if="column.dataIndex === 'opration'">
                                <a-button type="link" size="small" @click="showEdit(record)">编辑</a-button>
                                <a-popconfirm title="确定要删除吗？" @confirm="handleDeleteFaq(record)">
                                    <a-button type="link" size="small">删除</a-button>
                                </a-popconfirm>
                                <a-button type="link" size="small" @click="showPraise(record)">点赞</a-button>
                            </template>
                            <template v-if="column.dataIndex === 'remark'">
                                <div class="db-click" @dblclick="changeData(record)">{{ text || '--' }}</div>
                            </template>
                            <template v-if="column.dataIndex === 'solution'">
                                <div class="db-click-default" @dblclick="changeData(record)">{{ text || '--' }}</div>
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        getData()
    })
    function getData() {
        post('/solution-ppm/api/v2/built-in-system-ppm/project_question/search', state.filter).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.tableData = data.data
        })
    }
    function resetData() {
        state.filter.priorityList = state.filter.typeList = state.filter.questionSourceList = []
        getData()
    }
    function saveAsDefault() {
        put('/solution-ppm/api/v2/built-in-system-ppm/project_question/default_config', state.filter).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
        })
    }
    const columns = ref([
        {
            title: '序号',
            ellipsis: true,
            width: 100,
            dataIndex: 'number',
            align: 'center'
        },
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'projectName',
            align: 'center'
        },
        {
            title: '风险&问题简述',
            ellipsis: true,
            dataIndex: 'question',
            align: 'center'
        },

        {
            title: '优先级',
            ellipsis: true,
            width: 100,
            dataIndex: 'priority',
            align: 'center'
        },
        {
            title: '问题来源',
            ellipsis: true,
            width: 100,
            dataIndex: 'questionSource',
            align: 'center'
        },
        {
            title: '问题类型',
            ellipsis: true,
            width: 100,
            dataIndex: 'type',
            align: 'center'
        },
        {
            title: '状态',
            ellipsis: true,
            width: 100,
            dataIndex: 'status',
            align: 'center'
        },
        {
            title: '解决方案',
            ellipsis: true,
            dataIndex: 'solution',
            align: 'center'
        },
        {
            title: '解决人',
            dataIndex: 'solver',
            ellipsis: true,
            width: 100,
            align: 'center'
        },
        {
            title: 'PMO',
            dataIndex: 'pmo',
            ellipsis: true,
            width: 100,
            align: 'center'
        },
        {
            title: '计划完成时间',
            dataIndex: 'endTime',
            ellipsis: true,
            width: 150,
            align: 'center'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            ellipsis: true,
            width: 400,
            align: 'center'
        }
    ])
    const state = reactive({
        tableData: [],
        changeRemark: undefined,
        changeDataVisible: false,
        downLoading: false,
        filter: {
            'questionSourceList': [],
            'priorityList': [],
            'typeList': []
        }
    })
    function handlerGetSpace(data) {
        return data ? data.split(/[,，]/).map(item => item.trim()) : []
    }
    const handleIssued = () => {
        // try {
        //     state.downLoading = true
        //     // // 调用接口获取图片的 Base64 数据
        //     // const response = await post('/solution-ppm/api/v2/built-in-system-ppm/project_question/image', state.filter)
        //     // // 检查并去掉 MIME 类型前缀
        //     // let base64Data = response.data.split(',')[1]
        //     // // 下载图片
        //     // downloadImage(base64Data, '水泥配料项目问题&风险')
        // } catch (error) {
        //     state.downLoading = false
        //     console.error('下载图片失败：', error)
        // }
        state.downLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/project_question/image', state.filter)
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
            })
            .finally(() => {
                state.downLoading = false
            })
    }

    const downloadImage = (base64, name) => {
        const blob = base64ToBlob(base64)
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${name}.png` // 设置下载文件名
        link.click()
        URL.revokeObjectURL(url) // 释放 URL 对象
        state.downLoading = false
    }

    const base64ToBlob = base64 => {
        const binary = atob(base64)
        const array = []
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i))
        }
        return new Blob([new Uint8Array(array)], { type: 'image/png' })
    }
    const overStyle = ref({
        maxWidth: '300px',
        fontSize: '16px'
    })
    function handleResizeColumn(w, col) {
        if (col.title == '原因说明') {
            let div = document.querySelector('.omit-div')
            let width = w - 50
            div.style.width = width + 'px'
            overStyle.value.maxWidth = width + 'px'
        }

        col.width = w
    }
    const currentData = ref({})
    function changeData(record) {
        currentData.value = record
        state.changeRemark = cloneDeep(record.remark)
        state.changeDataVisible = true
    }
    function confirmReason() {
        currentData.value.remark = state.changeRemark
        put('/solution-ppm/api/v2/built-in-system-ppm/project_question/modify', currentData.value).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            state.changeDataVisible = false
            state.changeRemark = undefined
            currentData.value = {}
            getData()
        })
    }
    function cancelReason() {
        state.changeDataVisible = false
        state.changeRemark = undefined
        currentData.value = {}
    }
    import { saveAs } from 'file-saver'
    import * as XLSX from 'xlsx'
    // 导出为 Excel 的方法
    function exportToExcel(columns, tableData) {
        // 1. 动态生成表头和数据
        const headerList = columns.map(col => col.title)
        const worksheetData = tableData.map(item =>
            columns.reduce((acc, col) => {
                acc[col.title] = item[col.dataIndex] // 根据 dataIndex 获取对应字段
                return acc
            }, {})
        )

        // 2. 创建工作表和设置列宽度
        const worksheet = XLSX.utils.json_to_sheet(worksheetData)
        worksheet['!cols'] = columns.map(col => ({ wpx: col.width })) // 设置宽度

        // 3. 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

        // 4. 导出为二进制数据
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })

        // 5. 使用 FileSaver 保存文件
        saveAs(blob, 'table_data.xlsx')
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .default-table:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #3875ff;
        color: #fff;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9;
    }
    .default-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;

        .cell-wrapper {
            padding: 0 16px;
        }
    }
    .top-title {
        height: 16px;
        padding-left: 8px;
        border-left: 4px solid #3875ff;
        font-size: 16px;
        line-height: 16px;
        color: #262626;
        font-weight: 600;
    }
    /*样式*/
    .title {
        justify-content: space-between;
        display: flex;
        margin-bottom: 16px;
        align-items: center;
        font-weight: bold; /* 标题加粗 */
        height: 70px;
        border-bottom: 1px solid #d9d9d9;
    }
    .content {
        display: flex;
        gap: 16px;
    }
    .left {
        width: 50%;
        border: 1px solid #d9d9d9;
    }
    .right {
        flex: 1;
    }
    .description {
        padding: 8px 16px;
        border: 1px solid #d9d9d9;
    }
    .body {
        background-color: #fff;
        height: 100%;
        padding: 24px;
        padding-top: 0;
    }
    .text-line-div {
        text-decoration: underline;
        position: relative;
    }

    .db-click {
        width: 350px;
        line-height: 30px;
        cursor: pointer;
        white-space: pre-wrap;
        word-wrap: break-word;
    }
    .db-click-default {
        width: 350px;
        line-height: 30px;
        white-space: pre-wrap;
        word-wrap: break-word;
    }
    .red-color {
        color: #f5222d;
    }
    .omit-div {
        width: 320px;
        padding: 0 8px;
        min-height: 20px;
        height: 100px;
        white-space: pre-wrap;
        word-wrap: break-word;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3; /* 显示行数 */
        -webkit-box-orient: vertical;
    }
    .top-search {
        height: 64px;
        background-color: #fff;
        padding: 16px 24px;
        border-radius: 2px;
        margin-bottom: 16px;
    }
    .default-table :deep(.ant3-table-wrapper) {
        border-bottom: 1px solid #d9d9d9;
    }
    .page_root {
        overflow-y: hidden;
    }
</style>
